/**
 * 
 */
package com.antilia.infomaresme.pages.signin;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

import com.antilia.infomaresme.InfomaresmeSession;

/**
 * @author Ernesto
 *
 */
public abstract class LogInPanel extends Panel {

	private static final long serialVersionUID = 1L;

	private String username;
	
	private String password;
	
	private FeedbackPanel feedback;
	
	/**
	 * @param id
	 */
	public LogInPanel(String id) {
		super(id);
		
		setOutputMarkupId(true);
		Form<LogInPanel> form = new Form<LogInPanel>("form", 
				new CompoundPropertyModel<LogInPanel>(this));		
		add(form);
		TextField<String> username = new TextField<String>("username");
		form.add(username);
		PasswordTextField password = new PasswordTextField("password");
		password.setRequired(false);
		form.add(password);
		
		AjaxSubmitLink link = new AjaxSubmitLink("link") {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				form.error(getString("logIn.loginError"));
				target.add(feedback);
			}
			
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				if(InfomaresmeSession.getSession().authenticate(LogInPanel.this.username, LogInPanel.this.password)) {
					onLogIn(target);
				} else {
					form.error(getString("logIn.loginError"));
					target.add(feedback);
				}
				
			};
			
		};
		form.add(link);
		
		AjaxLink<Void> register = new AjaxLink<Void>("register") {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				onRegister(target);
			}
		};		
		form.add(register);
				
		
		AjaxLink<Void> recuperarContrasena = new AjaxLink<Void>("recuperarContrasena") {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				
			}
		};		
		
		form.add(recuperarContrasena);
		
		feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		add(feedback);
	}

	public abstract void onLogIn(AjaxRequestTarget target);
	
	public abstract void onRegister(AjaxRequestTarget target);
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
